package lookas.csvparser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import lookas.csvparser.converters.CurrencyConverter;
import lookas.csvparser.converters.DateConverter;
import lookas.csvparser.converters.DecimalConverter;
import lookas.dao.PersistenceDao;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wolainfo.simulator.model.tfi.Currency;

public class CsvParser{
    private static Log     log = LogFactory.getLog(CsvParser.class);
    private PersistenceDao persistenceDao;

    public int parse(Class<?> clazz) throws Exception{
        File f = new File("c:/projekty/arka/testowe/" + clazz.getSimpleName()
            + ".csv");
        return parse(f, clazz);
    }

    public int parse(File f, Class<?> output) throws Exception{
        String[] headers = Headers.getHeaders(output);
        FileReader r = new FileReader(f);
        BufferedReader x = new BufferedReader(r);
        String line;
        int l = 1;
        Set<Object> set = new HashSet<Object>();
        int warnCount = 0;
        ConvertUtils.register(new DateConverter(), Calendar.class);
        ConvertUtils.register(new DecimalConverter(), BigDecimal.class);
        ConvertUtils.register(new CurrencyConverter(), Currency.class);
        while((line = x.readLine()) != null){
            log.debug("parse line " + l++ + " of " + output.getName());
            String[] split = line.split("\t");
            Map<String, String> map = new HashMap<String, String>();
            for(int i = 0; i < Math.min(headers.length, split.length); i++){
                if(split[i] == null || "".equals(split[i])){
                    continue;
                }
                map.put(headers[i], split[i]);
            }
            Object instance = output.newInstance();
            BeanUtils.populate(instance, map);
            set.add(instance);
            warnCount += save(instance);
        }
        return warnCount;
    }

    private int save(Object o){
        try{
            persistenceDao.save(o);
            return 0;
        }catch(Exception e){
            return 1;
        }
    }

    public PersistenceDao getPersistenceDao(){
        return persistenceDao;
    }

    public void setPersistenceDao(PersistenceDao persistenceDao){
        this.persistenceDao = persistenceDao;
    }
}
